package com.asia5b.a5mall.middleware.logic.viewmodel.goods

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.asia5b.a5mall.middleware.base.SimpleNetParams
import com.asia5b.a5mall.middleware.base.SimpleViewModel
import com.asia5b.a5mall.middleware.cache.HsitoryCache
import com.asia5b.a5mall.middleware.model.bean.HistoryBean
import com.asia5b.a5mall.middleware.model.goods.HotModel
import com.asia5b.a5mall.middleware.model.goods.KeywordModel
import io.reactivex.Observable
import io.reactivex.functions.Consumer

/**
 * Created by zhangyuncai on 2020/1/11.
 */
class SearchKeyActivityVM : SimpleViewModel() {
    private val cache = HsitoryCache()

    val loadHotDatasLiveData = MutableLiveData<ArrayList<HotModel>>()
    fun loadHotDatas() {
        val observable = extraApi.getKeyword(10)
                .map {
                    return@map it
                }
        baseSubscribe(observable, SimpleNetParams(isToastError = false), Consumer { result ->
//            providerView().loadHotDatasResult(result)
            loadHotDatasLiveData.value = result
        })
    }

    val loadHistoryDatasLiveData = MutableLiveData<ArrayList<HistoryBean>>()
    fun loadHistoryDatas() {
        val history = Observable.create<ArrayList<HistoryBean>> {
            it.onNext(cache.get())
        }
        baseSubscribe(history, SimpleNetParams(isToastError = false), Consumer { result ->
//            providerView().loadHistoryDatasResult(result)
            loadHistoryDatasLiveData.value = result
        })
    }

    val getSearchKeywordLiveData = MutableLiveData<Array<Any>>()
    fun getSearchKeyword(keyword: String) {
        if (TextUtils.isEmpty(keyword)) {
            return
        }
        baseSubscribe(extraApi.getSearchKeyword(keyword), SimpleNetParams(isShowLoading = false), Consumer {
//            providerView().getSearchKeywordResult(it,keyword)
            getSearchKeywordLiveData.value = arrayOf(it, keyword)
        })
    }


    fun clearHistory() {
        cache.clear()
        loadHistoryDatas()
    }

    fun addHistory(item: HistoryBean) {
        cache.add(item)
        loadHistoryDatas()
    }

    fun deleteHistory(item: HistoryBean) {
        cache.delete(item)
        loadHistoryDatas()
    }
}